﻿using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;

namespace ZenSystemService.Api.Controllers
{
    [Route("api/[controller]")] // 指定控制器的路由为 api/filesync
    [ApiController] // 指示这是一个API控制器
    public class FileSyncController : ControllerBase
    {
        // 定义一个私有字段用于存储项目文件夹的根路径
        private readonly string baseFolderPath = ""; // 请替换为你的项目文件夹路径

        public FileSyncController(IConfiguration configuration)
        {
            var rootPath = configuration.GetValue<string>("ResourceServerRootPath");
            baseFolderPath = Path.Combine(rootPath, "projects");
        }
        [HttpPost("check-and-sync")]
        public IActionResult CheckAndSync([FromBody] ProjectFilesInfo projectFilesInfo)
        {
            var projectPath = Path.Combine(baseFolderPath, projectFilesInfo.ProjectName);
            if (!Directory.Exists(projectPath))
            {
                return NotFound("Project not found.");
            }

            // 获取服务器上项目文件夹中所有文件的信息（文件名和哈希值）
            var serverFiles = Directory.GetFiles(projectPath, "*", SearchOption.AllDirectories)
                .Select(f => new FileDetail
                {
                    FileName = f.Substring(projectPath.Length + 1), // 获取相对路径
                    Hash = ComputeHash(f) // 获取文件的哈希值
                }).ToList();

            var filesToUpdate = new List<FileDetail>();

            // 遍历服务器文件，检查哪些文件需要发送到客户端
            foreach (var serverFile in serverFiles)
            {
                var clientFile = projectFilesInfo.Files.FirstOrDefault(f => f.FileName == serverFile.FileName);
                if (clientFile == null || serverFile.Hash != clientFile.Hash)
                {
                    filesToUpdate.Add(serverFile);
                }
            }

            // 将需要更新的文件内容读取并返回给客户端
            var updatedFilesContent = filesToUpdate.Select(f => new FileContent
            {
                FileName = f.FileName,
                Content = System.IO.File.ReadAllBytes(Path.Combine(projectPath, f.FileName))
            }).ToList();

            return Ok(updatedFilesContent);
        }

        // 计算文件的哈希值（使用SHA256）
        private string ComputeHash(string filePath)
        {
            using (var sha256 = SHA256.Create())
            {
                using (var stream = System.IO.File.OpenRead(filePath))
                {
                    var hash = sha256.ComputeHash(stream);
                    return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
                }
            }
        }
    }

    public class ProjectFilesInfo
    {
        public string ProjectName { get; set; }
        public List<FileDetail> Files { get; set; }
    }

    public class FileDetail
    {
        public string FileName { get; set; }
        public string Hash { get; set; }
    }

    public class FileContent
    {
        public string FileName { get; set; }
        public byte[] Content { get; set; }
    }
}